﻿$(function () {
    Show()
})
function refesh() {
    location.reload();
}
//显示
function Show() {
    layui.use('table', function () {
        var form = layui.form;
        var table = layui.table;

        var checkNo = $("#checkNo").val();
        var createTime = $("#createTime").val();
        var auditStatus = $("#auditStatus").val();
        $.ajax({
            url: '../Warehouse/GetCheckShow', // 后端接口地址，需替换为实际地址
            type: 'get',
            data: {
                checkNo: checkNo,
                createTime: createTime,
                auditStatus: auditStatus || 0,
                PageIndex: 1,
                PageSize: 100,
                token: localStorage.getItem("token"),
            },
            success: function (res) {
                res = JSON.parse(res)
                // res 是从后端获取到的 JSON 数据
                if (res.code === 0) {
                    console.log(res.data.list);
                    table.render({
                        elem: checktable, // 对应 HTML 中表格的 id
                        data: res.data.list, // 绑定获取到的数据
                        toolbar: '#toolbarDemo',
                        defaultToolbar: ['exports'],
                        page: true,
                        limit: 5,
                        limits: [5, 8, 10],
                        cols: [[
                            { type: 'checkbox', fixed: 'left' },
                            { field: 'checkNo', title: '盘点单号' },
                            { field: 'checkType', title: '盘点类型' },
                            { field: 'associateNumber', title: '关联单号' },
                            { field: 'auditStatusText', title: '状态' },
                            { field: 'checkMakeHe', title: '制单人' },
                            {
                                field: 'createTime', title: '创建时间', templet: function (d) {
                                    return formatTime(d.createTime); // 调用自定义的时间格式转换函数
                                }
                            },
                            {
                                field: '', title: '操作', width: 300, templet: function (d) {
                                    return '<a class="layui-btn layui-btn-edit layui-btn-xs" lay-on="test-page-edit" onclick="updateData(' + d.checkId + ')"><i class="layui-icon layui-icon-edit"></i>编辑</a> ' +
                                        '<a class="layui-btn layui-btn-danger layui-btn-xs" onclick="deleteData(' + d.checkId + ')"><i class="layui-icon layui-icon-delete"></i>删除</a>' +
                                        '<a class="layui-btn layui-btn-edit layui-btn-xs" onclick="checkmodel(' + d.checkId + ')"><i class="layui-icon layui-icon-search"></i>查看</a>' +
                                        '<a class="layui-btn layui-btn-edit layui-btn-xs" onclick="uploadcheck(' + d.checkId + ')"><i class="layui-icon layui-icon-upload-circle"></i>上传</a>'
                                        ;
                                }
                            }
                        ]]
                    });
                } else {
                    console.log(res.msg);
                }
            },
            error: function () {
                console.log('获取数据失败');
            }
        });



        // 点击批量删除按钮的事件处理
        $('#batchDeleteBtn').click(function () {
            var checkStatus = table.checkStatus('checktable');
            var selectedIds = checkStatus.data.map(function (item) { return item.checkId; });
            console.log(selectedIds)
            if (selectedIds.length === 0) {
                layer.msg('请至少选择一条要删除的数据', { icon: 2 });
                return;
            }
            layer.confirm('确定要批量删除选中的 ' + selectedIds.length + ' 条数据吗？', function (index) {
                // 发送Ajax请求到后端，传递选中的id数组进行删除操作
                $.ajax({
                    url: '../Warehouse/GetCheckDelRange', // 后端批量删除接口地址，根据实际调整
                    type: 'POST',
                    data: { ids: JSON.stringify(selectedIds), token: localStorage.getItem("token") },
                    success: function (res) {
                        var res = JSON.parse(res)
                        console.log(res)
                        if (res.code > 0) {
                            layer.msg('批量删除成功', { icon: 1 });
                            Show()
                        } else {
                            layer.msg('批量删除失败：' + res.message, { icon: 2 });
                        }
                        layer.close(index);
                    },
                    error: function () {
                        layer.msg('请求出错，请稍后再试', { icon: 2 });
                        layer.close(index);
                    }
                });
            });
        });


        // 查看详情
        window.checkmodel = function (id) {
            // 先根据id获取要编辑的数据，发起Ajax请求
            $.ajax({
                type: "GET",
                url: "/Warehouse/GetFanCheck",  // 替换为实际的后台根据id获取数据的接口地址
                data: { checkId: id, token: localStorage.getItem("token") },
                success: (res) => {
                    try {
                        const { data } = JSON.parse(res);
                        console.log(data)
                        if (data) {
                            const { statisticsList } = data;
                            var check = data;
                            console.log(check);
                            console.log(statisticsList);
                            // 反填表单的函数
                            fillForm(check);
                            // 渲染表格的函数
                            renderTable(statisticsList);
                            console.log(statisticsList);
                            resolve(check, statisticsList);
                        } else {
                            layui.layer.msg(res.message, { icon: 2 });
                            reject(res.message);
                        }
                    } catch (e) {
                        //console.error(e);
                        //layui.layer.msg('数据解析失败，请稍后重试', { icon: 2 });
                        //reject('数据解析失败');
                    }
                },
                error: () => {
                    layui.layer.msg('获取用户信息失败，请稍后重试', { icon: 2 });
                    reject('获取用户信息失败');
                }
            });
            //$.ajax({
            //    url: '../Warehouse/GetAllocaitonShowbyid', // 后端接口地址，需替换为实际地址
            //    type: 'get',
            //    data: { allocationId: id, token: localStorage.getItem("token") },
            //    success: function (res) {
            //        console.log(res)
            //        var res = JSON.parse(res)
            //        // res 是从后端获取到的 JSON 数据
            //        if (res.code === 0) {
            //            console.log(res.data);
            //            table.render({
            //                elem: checkupLoad, // 对应 HTML 中表格的 id
            //                data: res.data, // 绑定获取到的数据
            //                cols: [[
            //                    { type: 'checkbox', fixed: 'left' },
            //                    { field: 'productName', title: '产品名称' },
            //                    { field: 'productNo', title: '产品编号' },
            //                    { field: 'productSpec', title: '规格' },
            //                    { field: 'productBatch', title: '批次' },
            //                    { field: 'binLocationName', title: '当前库位' },
            //                    { field: 'quantity', title: '数量' },
            //                    { field: 'quantity', title: '盘点数' },
            //                    { field: 'quantity', title: '盈亏数' },

            //                ]]
            //            });

            //        } else {
            //            console.log(res.msg);
            //        }
            //    },
            //    error: function () {
            //        console.log('获取数据失败');
            //    }
            //});

            layer.open({
                type: 1,
                title: '盘点单详情',
                content: `
                                     <form class="layui-form" action="">

                    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
                        <div class="layui-inline">
                            <label class="layui-form-label">盘点单号:</label>
                            <div class="layui-input-inline">
                                <input type="text" name="checkNos" id="checkNos" disabled lay-verify="required" autocomplete="off" class="layui-input">
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">关联订单号:</label>
                            <div class="layui-input-inline">
                                <input type="text" name="associateNumber" id="associateNumber" disabled lay-verify="required" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </div>

                    <div class="layui-form-item" style="margin-left:140px;margin-top:30px">
                        <div class="layui-inline">
                            <label class="layui-form-label">制单人:</label>
                            <div class="layui-input-inline">
                                <input type="text" name="checkMakeHe" id="checkMakeHe" disabled autocomplete="off" lay-verify="required" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">制单时间:</label>
                            <div class="layui-input-inline">
                                <input type="date" name="checkDate" id="checkDate" disabled autocomplete="off" lay-verify="required" class="layui-input">
                            </div>
                        </div>
                    </div>

                    <div class="layui-form-item" style="margin-left:140px;margin-top:30px">
                        <div class="layui-inline">
                            <label class="layui-form-label">单据状态:</label>
                            <div class="layui-input-inline">
                                <input type="text" name="auditStatusText" id="auditStatusText" disabled autocomplete="off" lay-verify="required" class="layui-input">
                            </div>
                        </div>
                        

                    </div>


                    <div class="layui-form-item layui-form-text" style="margin-left:130px;margin-top:30px">
                        <label class="layui-form-label">备注:</label>
                        <div class="layui-input-block">
                            <textarea placeholder="请输入内容" name="checkNotes" id="checkNotes" disabled lay-verify="required" class="layui-textarea"></textarea>
                        </div>
                    </div>
                    <table class="layui-hide" id="checkupLoad" lay-filter="test"></table>
                </form>
                <button type="button" class="layui-btn layui-btn-primary" style="margin-left:400px;margin-right:80px;margin-top:30px;"  onclick="location.href='/Warehouse/CheckShow'">关闭</button>
                                `,
                area: ['1000px', '700px'],
                success: function () {

                    // 对弹层中的表单进行初始化渲染
                    form.render();
                }
            });


        };
        var obj = {
            checkId: 0,
            productId: '',
            auditStatus: '',
            auditStatusText: '',
            checkType: '',
            office_id: '',
            user_id: '',
            examineReason: '',
            examinePeople: '',
            examineTime: '',
            createName: '',
            createTime: '',
            updateName: '',
            updateTime: '',
            deleteName: '',
            deleteTime: ''
        };
        // 反填表单的函数
        function fillForm(check) {
            $('#checkNos').val(check.checkNo);
            $('#associateNumber').val(check.associateNumber);
            $('#checkMakeHe').val(check.checkMakeHe);
            $('#checkNotes').val(check.checkNotes);
            $('#auditStatusText').val(check.auditStatusText);
            const date = new Date(check.checkDate);
            const year = date.getFullYear();
            const month = ("0" + (date.getMonth() + 1)).slice(-2);
            const day = ("0" + date.getDate()).slice(-2);
            $('#checkDate').val(year + "-" + month + "-" + day);
            $('#examineReason').val(check.examineReason);

            obj.checkId = check.checkId
            obj.productId = check.productId
            obj.auditStatus = check.auditStatus
            obj.auditStatusText = check.auditStatusText
            obj.checkType = check.checkType
            obj.office_id = check.office_id
            obj.user_id = check.user_id
            obj.examineReason = check.examineReason
            obj.examinePeople = check.examinePeople
            obj.examineTime = check.examineTime
            obj.createName = check.createName
            obj.createTime = check.createTime
            obj.updateName = check.updateName
            obj.updateTime = check.updateTime
            obj.deleteName = check.deleteName
            obj.deleteTime = check.deleteTime
            console.log(obj)
            // 重新渲染表单元素（如果有）
            //form.render();
        }

        // 渲染表格的函数
        function renderTable(statisticsList) {
            console.log(statisticsList);
            var checkId = statisticsList.checkId

            layui.use('table', function () {
                var table = layui.table;
                //查询
                $.ajax({
                    type: "get",
                    url: "/Warehouse/GetFanCheck",
                    data: {
                        checkId: checkId,
                        token: localStorage.getItem("token")
                    },
                    success: function (res) {
                        var obj = JSON.parse(res);
                        console.log(obj)
                        if (obj.code === 0) {
                            var inst = table.render({
                                elem: '#checkupLoad',//对应HTML中表格的id
                                data: statisticsList,//绑定获取的数据
                                cols: [[
                                    { field: 'productName', title: '产品名称' },
                                    { field: 'productNo', title: '产品编号' },
                                    { field: 'productSpec', title: '规格' },
                                    { field: 'statisticsBatch', title: '批次', edit: 'text' },
                                    {
                                        field: 'binLocationName', title: '库位'
                                    },
                                    { field: 'storageNum', title: '数量' },
                                    { field: 'statisticsSum', title: '盘点数' },
                                    {
                                        field: '', title: '盈亏数', templet: function (d) {
                                            return d.statisticsSum - d.storageNum;
                                        }
                                    },
                                ]]
                            })

                        } else {
                            console.log(res.msg);
                        }
                    },
                    error: function () {
                        console.log("获取数据失败");
                    }


                });



            });
        }

    });
}
// 定义删除数据的函数
window.deleteData = function (checkId) {
    console.log(checkId)
    layer.confirm('确定要删除该条数据吗？', function (index) {
        $.ajax({
            type: "Post",
            url: "../Warehouse/GetCheckDel",  // 替换为实际的后台删除数据接口地址
            data: { data: JSON.stringify({ checkId: checkId }), token: localStorage.getItem("token") },
            success: function (res) {
                var res = JSON.parse(res)
                if (res.code === 1) {
                    layer.alert("删除成功");
                    Show();  // 重新加载数据，刷新表格显示
                } else {
                    layer.alert("删除失败");

                }
            },
            error: function () {
                layer.msg('删除失败，请稍后重试', {
                    time: 2000,
                    icon: 2
                });
            }
        });
        layer.close(index);
    });
};


// 定义时间格式转换函数
function formatTime(timeStamp) {
    if (timeStamp) {
        var date = new Date(timeStamp);
        var year = date.getFullYear();
        var month = ('0' + (date.getMonth() + 1)).slice(-2);
        var day = ('0' + date.getDate()).slice(-2);
        var hour = ('0' + date.getHours()).slice(-2);
        var minute = ('0' + date.getMinutes()).slice(-2);
        var second = ('0' + date.getSeconds()).slice(-2);
        return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
    }
    return "";
}

// 点击表格上方编辑按钮的事件处理
$('#batchUpdBtn').click(function () {
    var table = layui.table;
    var checkStatus = table.checkStatus('checktable');
    var selectedIds = checkStatus.data.map(function (item) { return item.checkId; });
    console.log(selectedIds)
    if (selectedIds.length === 0) {
        layer.msg('请选择一条要编辑的数据', { icon: 2 });
        return;
    }
    localStorage['checkId'] = selectedIds;
    location.href = '/Warehouse/CheckUpd';
});




//盘点编辑
window.updateData = function (checkId) {
    localStorage['checkId'] = checkId;
    location.href = '/Warehouse/CheckUpd';
}

//上传盘点单结果
window.uploadcheck = function (checkId) {
    localStorage['checkId'] = checkId;
    location.href = '/Warehouse/CheckupLoad';
}


//仓库类型下拉框
layui.use('form', function () {
    var form = layui.form;
    $.ajax({
        url: "../Warehouse/GetAduiStatusShow",
        type: "get",
        data: { token: localStorage.getItem("token") },
        success: function (data) {
            var obj = JSON.parse(data);
            console.log(obj)
            var options = '<option value="">请选择</option>'; // 添加默认选项
            $.each(obj, function (index, item) {
                options += '<option value="' + item.value + '">' + item.text + '</option>';
            });
            $("#auditStatus").html(options);
            form.render('select'); // 重新渲染下拉框
        },
        error: function () {
            console.log("获取数据失败");
        }
    });
});